package com.mission.schedule.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.mission.schedule.R;
import com.mission.schedule.annotation.ViewResId;
import com.mission.schedule.applcation.App;
import com.mission.schedule.bean.qd606.CLInventoryListBean;
import com.mission.schedule.bean.qd606.NoteTitleDetailBean;
import com.mission.schedule.bean.qd606.UpLoadQdBean;
import com.mission.schedule.constants.ShareFile;
import com.mission.schedule.constants.URLConstants;
import com.mission.schedule.service.NoteService;
import com.mission.schedule.utils.NetUtil;
import com.mission.schedule.utils.ProgressUtil;
import com.mission.schedule.utils.SharedPrefUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

@SuppressLint({"SimpleDateFormat", "HandlerLeak"})
public class AddQDListSetActivity extends BaseActivity implements OnClickListener {

    @ViewResId(id = R.id.top_ll_back)
    private LinearLayout top_ll_back;
    @ViewResId(id = R.id.rl2)
    private RelativeLayout rl2;
    @ViewResId(id = R.id.ll1)
    private LinearLayout ll1;
    @ViewResId(id = R.id.rl1)
    private RelativeLayout rl1;
    @ViewResId(id = R.id.image_icon)
    private ImageView image_icon;
    @ViewResId(id = R.id.copy_tv)
    private TextView copy_tv;
    @ViewResId(id = R.id.rl4)
    private RelativeLayout rl4;
    @ViewResId(id = R.id.fd_tv)
    private TextView fd_tv;

    Context context;
    App application = App.getDBcApplication();

    String addicon, addcopy,addfenduan;

    SharedPrefUtil sharedPrefUtil = null;


    @Override
    protected void setListener() {
        top_ll_back.setOnClickListener(this);
        rl2.setOnClickListener(this);
        rl1.setOnClickListener(this);
        rl4.setOnClickListener(this);
        ll1.setOnClickListener(this);
    }

    String titleid = "0";
    String userid = "0";
    boolean isnewlist = false;

    int[] images = {R.mipmap.icon_beiwang, R.mipmap.icon_putong, R.mipmap.icon_buy, R.mipmap.icon_xinyuan, R.mipmap.icon_renwu};

    @Override
    protected void setContentView() {
        setContentView(R.layout.add_qdlist_set);
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        context = this;
        sharedPrefUtil = new SharedPrefUtil(context, ShareFile.USERFILE);
        userid = sharedPrefUtil.getString(context, ShareFile.USERFILE,
                ShareFile.USERID, "");
        addcopy = sharedPrefUtil.getString(context, ShareFile.USERFILE,
                ShareFile.ADDQDCOPY, "0");//0底部1顶部
        addicon = sharedPrefUtil.getString(context, ShareFile.USERFILE,
                ShareFile.ADDQDICON, "0");
        addfenduan = sharedPrefUtil.getString(context, ShareFile.USERFILE,
                ShareFile.ADDFENDUAN, "0");// 0 分段 1 不分段

        titleid = getIntent().getStringExtra("titleid");
        isnewlist = getIntent().getBooleanExtra("isnew", false);
//        if (!isnewlist) {
//            ll1.setVisibility(View.VISIBLE);
//        } else {
//            ll1.setVisibility(View.GONE);
//        }
        loadData();
    }

    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case -1:
                    break;
            }
        }
    };

    private void loadData() {
        image_icon.setBackgroundResource(images[Integer.valueOf(addicon)]);
        if (addcopy.equals("0")) {
            copy_tv.setText("底部");
        } else {
            copy_tv.setText("顶部");
        }

        if (addfenduan.equals("1")) {
            fd_tv.setText("不分段");
        } else {
            fd_tv.setText("分段");
        }
    }


    @Override
    protected void setAdapter() {
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.top_ll_back:
                this.finish();
                break;
            case R.id.rl2:
                Intent intent = new Intent(context, AddQDListIconActivity.class);
                startActivityForResult(intent, 602);
                break;
            case R.id.rl1:
                if (addcopy.equals("1")) {
                    sharedPrefUtil.putString(context, ShareFile.USERFILE,
                            ShareFile.ADDQDCOPY, "0");
                    copy_tv.setText("顶部");
                } else {
                    sharedPrefUtil.putString(context, ShareFile.USERFILE,
                            ShareFile.ADDQDCOPY, "1");
                    copy_tv.setText("底部");
                }
                addcopy = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.ADDQDCOPY, "1");//1底部2顶部
                break;
            case R.id.rl4:
                if (addfenduan.equals("1")) {
                    sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.ADDFENDUAN, "0");
                    fd_tv.setText("分段");
                } else {
                    sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.ADDFENDUAN, "1");
                    fd_tv.setText("不分段");
                }
                addfenduan = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.ADDFENDUAN, "0");
                break;
            case R.id.ll1:
                updateBeanToJson(titleid);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        addicon = sharedPrefUtil.getString(context, ShareFile.USERFILE,
                ShareFile.ADDQDICON, "0");
        loadData();
        super.onActivityResult(requestCode, resultCode, data);
    }

    private ProgressUtil progressUtil = new ProgressUtil();

    /**
     * 同步,去除当前标题ID的所有清单,并取出updateState
     */
    private void updateBeanToJson(String maxTitleId) {
        progressUtil.ShowProgress(context, true, true, "清单同步中");
        List<NoteTitleDetailBean.TDelListBean> tDelListBeanList = App.getDBcApplication().getAllNoteTitlesData(userid, true);
        JSONObject tDelListBeanListjsonObject = new JSONObject();
        try {
            JSONArray tDelListBeanListjsonArray = new JSONArray();
            for (NoteTitleDetailBean.TDelListBean bean : tDelListBeanList) {
                JSONObject js = new JSONObject();
                js.put("id", bean.id);
                js.put("titleId", bean.titleId);
                js.put("uid", bean.uid);
                js.put("titles", bean.titles);
                js.put("imgPath", bean.imgPath);
                js.put("imgUrl", bean.imgUrl);
                js.put("shareUrl", bean.shareUrl);
                js.put("filed", bean.filed);
                js.put("nums", bean.nums);
                js.put("copys", bean.copys);
                js.put("styles", bean.styles);
                js.put("ltype", bean.ltype);
                js.put("orderId", bean.orderId);
                js.put("createTime", bean.createTime);
                js.put("changeTime", bean.changeTime);
                js.put("localTimes", bean.localTimes);
                js.put("remark", bean.remark);
                js.put("remark1", bean.remark1);
                js.put("remark2", bean.remark2);
                js.put("remark3", bean.remark3);
                js.put("updateState", bean.id < 0 ? 1 : App.getDBcApplication().getNoteTitleState(bean.titleId, userid));
                tDelListBeanListjsonArray.put(js);
            }

            if (tDelListBeanList.size() > 0) {
                tDelListBeanListjsonObject.put("classTitle", tDelListBeanListjsonArray);
            } else {
                tDelListBeanListjsonObject = null;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //详情
        List<NoteTitleDetailBean.ListBean> listBeanList = App.getDBcApplication().getAllNoteDetailData(userid, true);
        JSONObject listjsonObject = new JSONObject();
        try {
            JSONArray listjsonArray = new JSONArray();
            for (NoteTitleDetailBean.ListBean bean : listBeanList) {
                JSONObject js = new JSONObject();
                js.put("id", bean.id);
                js.put("titleId", bean.titleId);
                js.put("uid", bean.uid);
                js.put("titles", bean.titles);
                js.put("imgPath", bean.imgPath);
                js.put("imgUrl", bean.imgUrl);
                js.put("shareUrl", bean.shareUrl);
                js.put("contents", bean.contents);
                js.put("nums", bean.nums);
                js.put("style", bean.style);
                js.put("endstate", bean.endstate);
                js.put("lType", bean.lType);
                js.put("orderId", bean.orderId);
                js.put("createTime", bean.createTime);
                js.put("changeTime", bean.changetime);
                js.put("cpath", bean.cpath);
                js.put("curl", bean.curl);
                js.put("remark", bean.remark);
                js.put("remark1", bean.remark1);
                js.put("remark2", bean.remark2);
                js.put("remark3", bean.remark3);
                js.put("remark4", bean.remark4);
                js.put("updateState", bean.id < 0 ? 1 : App.getDBcApplication().getNoteTitleDetailState(bean.titleId, userid, bean.id));
                listjsonArray.put(js);
            }
            if (listBeanList.size() > 0) {
                listjsonObject.put("class1", listjsonArray);
            } else {
                listjsonObject = null;
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        uploadListData(listjsonObject == null ? "" : listjsonObject.toString(), tDelListBeanListjsonObject == null ? "" : tDelListBeanListjsonObject.toString());

    }


    /**
     * 上传清单数据
     */
    private void uploadListData(String data, String dataTitle) {
        if (NetUtil.getConnectState(this) == NetUtil.NetWorkState.NONE) {
            Toast.makeText(context, "网络异常，请检查网络！", Toast.LENGTH_SHORT).show();
        } else {
            HttpUtils httpUtils = new HttpUtils(10000);
            RequestParams params = new RequestParams();
            params.addBodyParameter("data", data);
            params.addBodyParameter("dataTitle", dataTitle);
            httpUtils.send(HttpMethod.POST, URLConstants.清单和清单标题上行, params,
                    new RequestCallBack<String>() {

                        @Override
                        public void onFailure(HttpException e, String msg) {
                            progressUtil.dismiss();
                            Log.e("TAG", "上传失败！");
                        }


                        @Override
                        public void onSuccess(ResponseInfo<String> responseInfo) {
                            if (!TextUtils.isEmpty(responseInfo.result)) {
                                Gson gson = new Gson();
                                NoteService.noteSynBean bean = gson.fromJson(responseInfo.result, NoteService.noteSynBean.class);
                                if (bean.status == 0) {
                                    List<NoteService.noteSynBean.TDelListBean> tDeListBeanList = bean.tDelList;

                                    //标题同步没有异常
                                    List<Integer> errorList = new ArrayList<Integer>();

                                    for (NoteService.noteSynBean.TDelListBean tDeListBean : tDeListBeanList) {
                                        if (tDeListBean.dataState == 1) {//新增
                                            if (tDeListBean.state == 0) {//成功
                                                //修改id和状态值
                                                App.getDBcApplication().updateNoteTitleId(tDeListBean.id, tDeListBean.calendId, userid);
                                                App.getDBcApplication().updateNoteTitleState(tDeListBean.calendId + "", userid, 0, true);

                                            } else if (tDeListBean.state == 1) {//失败  可以不操作,但是避免意外
                                                //更改状态为1
                                                App.getDBcApplication().updateNoteTitleState(tDeListBean.id + "", userid, 1, true);
                                            } else if (tDeListBean.state == 2) { //异常
                                                App.getDBcApplication().updateNoteTitleState(tDeListBean.id + "", userid, -1, true);
                                                errorList.add(tDeListBean.id);
                                            }
                                        } else if (tDeListBean.dataState == 2) {//修改
                                            if (tDeListBean.state == 0) {//成功
                                                //修改该id状态值
                                                App.getDBcApplication().updateNoteTitleState(tDeListBean.id + "", userid, 0, true);
                                            } else if (tDeListBean.state == 1) {//失败
                                                //更改状态为2
                                                App.getDBcApplication().updateNoteTitleState(tDeListBean.id + "", userid, 2, true);
                                            } else if (tDeListBean.state == 2) { //异常
                                                App.getDBcApplication().updateNoteTitleState(tDeListBean.id + "", userid, -1, true);
                                                errorList.add(tDeListBean.id);
                                            }
                                        } else if (tDeListBean.dataState == 3) {//删除
                                            if (tDeListBean.state == 0) {//成功
                                                //删除该id的清单
                                                App.getDBcApplication().deleteNoteTitleData(tDeListBean.id, userid, true);
                                            } else if (tDeListBean.state == 1) {//失败
                                                //更改状态为3
                                                App.getDBcApplication().updateNoteTitleState(tDeListBean.id + "", userid, 3, true);
                                            } else if (tDeListBean.state == 2) { //异常
                                                App.getDBcApplication().updateNoteTitleState(tDeListBean.id + "", userid, -1, true);
                                                errorList.add(tDeListBean.id);
                                            }
                                        }
                                    }

                                    if (errorList.size() == 0) {

                                        List<NoteService.noteSynBean.ListBean> listBeans = bean.list;

                                        for (NoteService.noteSynBean.ListBean listBean : listBeans) {

                                            if (listBean.dataState == 1) {//新增
                                                if (listBean.state == 0) {//成功
                                                    //修改id和状态值
                                                    App.getDBcApplication().updateNoteDetailId(listBean.id, listBean.calendId, userid);
                                                    App.getDBcApplication().updateNoteTitleDetailState("", listBean.calendId, userid, 0, true);
                                                } else if (listBean.state == 1) {//失败  可以不操作,但是避免意外
                                                    //更改状态为1
                                                    App.getDBcApplication().updateNoteTitleDetailState("", listBean.id, userid, 1, true);
                                                } else if (listBean.state == 2) { //异常
                                                    App.getDBcApplication().updateNoteTitleDetailState("", listBean.id, userid, -1, true);
                                                }
                                            } else if (listBean.dataState == 2) {//修改
                                                if (listBean.state == 0) {//成功
                                                    //修改该id状态值
                                                    App.getDBcApplication().updateNoteTitleDetailState("", listBean.id, userid, 0, true);
                                                } else if (listBean.state == 1) {//失败
                                                    //更改状态为2
                                                    App.getDBcApplication().updateNoteTitleDetailState("", listBean.id, userid, 2, true);
                                                } else if (listBean.state == 2) { //异常
                                                    App.getDBcApplication().updateNoteTitleDetailState("", listBean.id, userid, -1, true);
                                                }
                                            } else if (listBean.dataState == 3) {//删除
                                                if (listBean.state == 0) {//成功
                                                    //删除该id的清单
                                                    App.getDBcApplication().deleteNoteTitledetailData(listBean.id, userid, true);
                                                } else if (listBean.state == 1) {//失败
                                                    //更改状态为3
                                                    App.getDBcApplication().updateNoteTitleDetailState("", listBean.id, userid, 3, true);
                                                } else if (listBean.state == 2) { //异常
                                                    App.getDBcApplication().updateNoteTitleDetailState("", listBean.id, userid, -1, true);
                                                }
                                            }
                                        }
                                        sharedPrefUtil.putString(
                                                getApplication(),
                                                ShareFile.USERFILE,
                                                ShareFile.DOWNREPTIME,
                                                bean.downTime.replace(
                                                        "T", " "));
                                        Toast.makeText(context,"同步成功",Toast.LENGTH_SHORT).show();
                                        progressUtil.dismiss();
                                    }else {
                                        progressUtil.dismiss();
                                        Toast.makeText(context,"网络异常",Toast.LENGTH_SHORT).show();
                                    }
                                } else {
                                    progressUtil.dismiss();
                                    Toast.makeText(context,"网络异常",Toast.LENGTH_SHORT).show();
                                }
                            }
                        }
                    });

        }
    }
}
